<template>
    <a-modal title="批量导入协议" :width="800" :visible="visible" :confirmLoading="submitLoading" :footer="null" @cancel="visible=false">
        <a-alert style="margin-bottom: 20px" description="只能上传线下任务的合同。批量上传协议名称命名规则：身份证号码（500110xxxxxxx1316.pdf）。批量上传协议时，单个文件不能大于10MB。一次上传限制100个文件" closable type="info" />

        <a-progress v-if="count>0" status="normal" :percent="count" :format="getProgressText"/>

        <input v-show="false" ref="fileRef" accept="application/pdf" type="file" multiple @change="fileChange">
        <div class="idcard-clss" v-if="fileList.length > 0">
            <div class="idcard-item" v-for="(item,index) in fileList" :key="index">
                <p>{{item.name}}</p>
                <a-button class="upload-icon" @click="del(index)" type="link" icon="close-circle"></a-button>
            </div>
        </div>
        
        <a-empty v-if="fileList.length === 0" />        
        <div class="custom-drawer-footer">
            <div style="float: left">
                <label>{{userInfo.type === 2 ?'选择园区：':'选择企业：'}}</label>
                <a-select v-model="sourceId"
                    style="width: 180px"
                    showSearch
                    allowClear
                    placeholder="请选择"
                    :options="sourceData"
                    :filter-option="filterOption">
                </a-select>
            </div>
            <a-button @click="$refs.fileRef.click()" icon="upload">批量上传协议</a-button>
            <a-popconfirm
                title="取消后，数据清空，是否取消?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="visible=false" >
                <a-button>取消</a-button>
            </a-popconfirm>
            <a-button type="primary" :disabled="btnState" @click="submitTaskTemp">提交</a-button>
        </div>
    </a-modal>
</template>
<script>
import { mapGetters } from 'vuex'
import store from '@/store'
import {sysBaseUpload} from '@/api/manage/base'
import {allContractBatchImprotFile} from '@/api/manage/sign'
export default {
    name: 'ContractUpload',
    data () {
        return {
            fileList:[],
            visible:false,
            count:0,
            flag:false,
            sourceId:'',
            submitLoading:false,
            sourceData:[]
        }
    },
    computed: {
        ...mapGetters(['userInfo']),
        btnState(){
            var flag = false;
            if(this.flag === true && this.count !== 100 || this.fileList.length == 0){
                flag = true;
            }
            return flag;
        }
    },
    methods:{
        add(item){
            this.fileList = [];
            this.count = 0;
            this.sourceId = '';
            this.flag = false;
            this.initConpany();
            this.visible = true;
        },
        async initConpany(){
            if(this.userInfo.type === 2){
                let paramsEnterprise = {enterpriseId:this.userInfo.relationId}
               const {data} = await store.dispatch('getEnterpriseOrParkEnabled',paramsEnterprise);
                data && data.forEach(v=>{
                v.value = v.parkId;
                v.label = v.name;
                })
               this.sourceData = data;
            }else if(this.userInfo.type === 3){
                let paramsPark = {parkId:this.userInfo.relationId}
                this.sourceData = await store.dispatch('parkIdGetEnterpriseList',paramsPark);
            }
        },
        filterOption(inputValue,option){
            return option.componentOptions.children[0].text.toLowerCase().indexOf(inputValue) >= 0
        },
        getProgressText(percent){
            return`${percent}% `
        },
        async fileChange(e) {
            this.count = 0;
            this.flag = true;
            let fileList = e.target.files;
            if(fileList.length===0){
                this.flag = false;
                e.target.value= "";
                return;
            }
            if(fileList.length > 100){
                this.flag = false;
                e.target.value= "";
                this.$message.error("一次只能上传100个文件");
                return;
            }
            
            for (var i = 0;i < fileList.length;i++){
                 let fileIndex= fileList[i].name.lastIndexOf(".");
                let fileName = fileList[i].name.substring(0,fileIndex);
                if (fileList[i].type.indexOf('pdf') === -1) {
                    e.target.value = '';
                    this.flag = false;
                    this.$message.error("只支持pdf格式");
                    return;
                }
                const isLt1m = fileList[i].size / 1024 / 1024 < 10;
                if (!isLt1m) {
                    e.target.value = '';
                    this.flag = false;
                    this.$message.error("单个文件不得大于10MB!");
                    return false;
                }
                let formData = new FormData();
                formData.append("file",fileList[i]);
                const {code,data} = await sysBaseUpload(formData);
                if(code === '1'){
                    this.count++;
                    this.fileList.push({idCardFront:data,name:fileName});
                    if(this.count === fileList.length){
                         this.count = 100;
                         this.flag = false;
                         e.target.value= "";
                         this.$message.success('操作成功');
                    }
                }
            }
        },
        del(index){
            this.fileList.splice(index,1);
            if(this.fileList.length === 0){
                this.count = 0;
            }
        },
        async submitTaskTemp(){
            if(!this.sourceId && this.userInfo.type === 2){
                return this.$message.error('请选择企业')
            }
             if(!this.sourceId && this.userInfo.type === 3){
                return this.$message.error('请选择园区')
            }
            let params = {};
            let str = {data:this.fileList};
            params.param = JSON.stringify(str);    
            params.sourceId = this.sourceId;
            this.submitLoading = true;
            const {code} = await allContractBatchImprotFile(params);
            this.submitLoading = false;
            if(code === '1'){
                this.$message.success('操作成功');
                this.visible = false;
                this.$emit("on-ok");
           }
        }
    }
}
</script>
<style scoped>
    .idcard-clss{
        height: 300px;
        overflow: auto;
    }
    .idcard-item{
        margin-top: 15px;
        position: relative;
    }
    .idcard-item p{
        font-size: 14px;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        overflow: hidden;
    }
    .upload-icon{
        position: absolute;
        top: -6px;
        right: 0;
        font-size: 20px;
    }
    
</style>